// logger.js
const winston = require('winston')
require('winston-daily-rotate-file')
const { combine, timestamp, printf, colorize } = winston.format
const logFormat = printf(({ level, message, timestamp, ...metadata }) => {
  let msg = `${timestamp} [${level}] : ${message} `
  if (metadata) {
    msg += JSON.stringify(metadata)
  }
  return msg
})
// 创建 logger 实例并设置配置
const logger = winston.createLogger({
  // 定义日志消息的格式
  format: combine(colorize(), timestamp(), logFormat),
  transports: [
    // 控制台日志配置
    new winston.transports.Console({
      level: 'debug',
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.printf(
          info => `[${info.timestamp}] ${info.level}: ${info.message}`
        )
      )
    }),
    // 文件日志配置
    new winston.transports.DailyRotateFile({
      filename: 'logs/application-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '14d' // 日志文件保留14天
    })
  ]
})
module.exports = logger
